package server

import (
	"fmt"
	"npxy-go/pkg/proxy/message"
	"npxy-go/pkg/proxy/server/rest"
	"npxy-go/pkg/tcp"
	"npxy-go/pkg/tcp/handlers"
)

func Start(conf *Config) error {
	bhs := make(map[string]rest.Bridge)

	if conf.APIEnable {
		rest.ServeHttp(conf.APIPort, bhs)
	}

	bridge := tcp.NewServer(func(pipe tcp.Pipeline) {
		pipe.AddHandlerChain(
			handlers.NewLengthHeadHandler(),
			handlers.NewServerAuthorizeHandler(conf.Secret),
			createBridgeHandler(pipe.String(), bhs),
		)
	})
	bridge.ReadBufferSize = tcp.DefaultReadBufferSize + message.TotalHeadSize
	bridge.ReadHeadSize = 0

	return bridge.ListenAndServe(fmt.Sprintf(":%d", conf.BridgePort))
}

func createBridgeHandler(addr string, bhs map[string]rest.Bridge) *bridgeHandler {
	bh := &bridgeHandler{}
	bh.connectCallback = func() {
		bhs[addr] = bh
	}
	bh.disconnectCallback = func() {
		delete(bhs, addr)
	}
	return bh
}
